import { FMVCS } from "../../fgui/fmvc/FMVCS";
import PlayerData from "./PlayerData";
import { GlobalEvent } from "../global/Global";
import { ConstDefine } from "../common/ConstDefine";
import { UpdateUserInfo, UserRelogin, UserLogin } from "../../gamenet/protobufs/userprotocol/protocol_001";

export default class PlayerCtrl extends FMVCS.FCtrl {
    static instance: PlayerCtrl = null;
    /** 数据实体 */
    static data: PlayerData = null;
    /** 游客密钥 */
    code: string = null;

    constructor() {
        super();
        PlayerCtrl.instance = this;
        PlayerCtrl.data = new PlayerData();
    }

    /** 事件监听注册 */
    rigisterEventListener() {
        this.on(GlobalEvent.GameEventID.GameResult, this.onGameResult, this);
        this.rigisterProtocol(UpdateUserInfo, `onUpdateUserInfoRecv`);
        this.rigisterProtocol(UserRelogin, `onUserReloginRecv`);
    }

    // guestLogin() {
    //     this.code = cc.sys.localStorage.getItem("guest_key");
    //     let protocol = ProtocolPool.instance.getProtocol(GuestLogin);
    //     protocol.code = this.code;
    //     protocol.encodeAndSend();
    // }

    onGameResult(data: ConstDefine.Result.ResultEventData) {
        let isWin = data.isWin;
        let level = data.level;
        if (isWin) {
            if (data.pattern == ConstDefine.GameMain.Pattern.normal && level == PlayerCtrl.data.vo.maxLevel) {
                PlayerCtrl.data.vo.maxLevel++;
                PlayerCtrl.data.saveData();
            }
        }
    }

    onUpdateUserInfoRecv(protocol: UpdateUserInfo) {
        let playerVo = PlayerCtrl.data.vo;
        playerVo.nickName = protocol.nickName;
        playerVo.icon = protocol.icon;
        playerVo.country = protocol.country;
        playerVo.province = protocol.province;
        playerVo.city = protocol.city;
        playerVo.language = protocol.language;
        playerVo.face = protocol.face;
        playerVo.sex = protocol.sex;
        playerVo.vip = protocol.vip;
        this.emit(GlobalEvent.GameEventID.UpdateUserInfo);
    }

    onUserReloginRecv(protocol: UserLogin) {
        this.emit(GlobalEvent.UIListenID.UI_ShowTips, `你的账号在别的地方登录!`, () => {
            cc.game.end();
        });
    }
}
